package com.py.credit.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.dao.BusinessModelBindDao;
import com.py.credit.dao.ModelBaseDao;
import com.py.credit.dao.ModelTestDao;
import com.py.credit.entity.ModelTestPc;
import com.py.credit.service.BusinessModelBindService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.SQLBuilder;
import com.py.framework.core.common.Page;
import com.py.framework.core.entity.SysOfficeEntity;
import com.py.framework.core.helper.UrlHelper;
import com.py.framework.core.http.HttpAgent;

@Service
public class BusinessModelBindServiceImpl implements BusinessModelBindService{

	@Autowired
	private BusinessModelBindDao businessModelBindDao;
	@Autowired
	private UrlHelper urlHelper;
	@Autowired
	private ModelTestDao modelTestDao;
	@Autowired
	private ModelBaseDao modelBaseDao;
	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;
	
	@Override
	public void insertIntoBusiness(Map<String, String> map) {

		businessModelBindDao.insertIntoBusiness(map);
	}
	@Override
	public void updateBusiness(Map<String, String> map) {
		businessModelBindDao.updateBusiness(map);		
	}
	@Override
	public void deleteBusiness(List<Integer> list) {
		businessModelBindDao.deleteBusiness(list);
	}
	@Override
	public String selectModelId(String name) {
		return businessModelBindDao.selectModelId(name);
	}
	
	@Override
	public List<Map<String, Object>> getByConditionForPage(List<String> columns, String[] additionalColumns,
			String conditionStr, Page page) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		List<Map<String, Object>> batchLogs = businessModelBindDao.selectByConditionForPage(columns, additionalColumns,
				conditions, page);

		return batchLogs;
	}
	@Override
	public Map<String, Integer> countScoreRank(String pcId) {
		return businessModelBindDao.countScoreRank(pcId);
	}
	@Override
	public List<String> countChartByPer(String pcId) {
		return businessModelBindDao.countChartByPer(pcId);
	}
	
	@Override
	 public RestServiceResult<List<Map<String,Object>>> countChartByPerFar(String  tybms, String jdToken) {
	        String url = urlHelper.getPlatformServerUrl() + "/enterpriseFamilyJa/calChartByPer.json";
	        Map<String, String> params = new HashMap<String, String>(1);
	        params.put("tybms", tybms);
	        String result = "";
	        try {
	            // 发送请求
	            result = HttpAgent.getInstance().sendHttpPost(url, params, jdToken);
	            return JSONObject.parseObject(result, new TypeReference<RestServiceResult<List<Map<String,Object>>>>() {
	            });
	        } catch (Exception e) {
	            RestServiceResult<List<Map<String,Object>>> areaData = new RestServiceResult<List<Map<String,Object>>>();
	            areaData.setCode(RestServiceResult.CODE_UNKNOW);
	            areaData.setMsg("系统异常，请稍后再试！");
	            ExceptionLogger.error("远程服务-通过tybm获取饼图调用异常！(businessModelBindServideImpl#countChartByPer) URL:" + url + " Params:"
	                    + params.toString() + "Result:" + result, e.getMessage(), e);
	            return areaData;
	        }
	    }
	
	@Override
	 public RestServiceResult<Map<String,Object>> getQyinfos(String  tybm, String jdToken) {
	        String url = urlHelper.getPlatformServerUrl() + "/enterpriseFamilyJa/getQyinfos.json";
	        Map<String, String> params = new HashMap<String, String>(1);
	        params.put("tybm", tybm);
	        String result = "";
	        try {
	            // 发送请求
	            result = HttpAgent.getInstance().sendHttpPost(url, params, jdToken);
	            return JSONObject.parseObject(result, new TypeReference<RestServiceResult<Map<String,Object>>>() {
	            });
	        } catch (Exception e) {
	            RestServiceResult<Map<String,Object>> areaData = new RestServiceResult<Map<String,Object>>();
	            areaData.setCode(RestServiceResult.CODE_UNKNOW);
	            areaData.setMsg("系统异常，请稍后再试！");
	            ExceptionLogger.error("远程服务-通过tybm获取饼图调用异常！(businessModelBindServideImpl#countChartByPer) URL:" + url + " Params:"
	                    + params.toString() + "Result:" + result, e.getMessage(), e);
	            return areaData;
	        }
	    }
	
	@Override
	 public RestServiceResult<Map<String,Object>> blackOrRed(String  tybm, String jdToken) {
	        String url = urlHelper.getPlatformServerUrl() + "/enterpriseFamilyJa/blackOrRed.json";
	        Map<String, String> params = new HashMap<String, String>(1);
	        params.put("tybm", tybm);
	        String result = "";
	        try {
	            // 发送请求
	            result = HttpAgent.getInstance().sendHttpPost(url, params, jdToken);
	            return JSONObject.parseObject(result, new TypeReference<RestServiceResult<Map<String,Object>>>() {
	            });
	        } catch (Exception e) {
	            RestServiceResult<Map<String,Object>> areaData = new RestServiceResult<Map<String,Object>>();
	            areaData.setCode(RestServiceResult.CODE_UNKNOW);
	            areaData.setMsg("系统异常，请稍后再试！");
	            ExceptionLogger.error("远程服务-通过tybm获取饼图调用异常！(businessModelBindServideImpl#countChartByPer) URL:" + url + " Params:"
	                    + params.toString() + "Result:" + result, e.getMessage(), e);
	            return areaData;
	        }
	    }
	
	@Override
	public List<Map<String, Object>> getBindByConditionForPage(String officeId,String modelName,String showScoreLine,List<String> columns, String[] additionalColumns,
			String conditionStr, Page page) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		List<Map<String, Object>> batchLogs = businessModelBindDao.getBindByConditionForPage(officeId, modelName, showScoreLine,columns, additionalColumns,
				conditions, page);
		return batchLogs;
	}
	@Override
	public Map<String, Object> getBindInfo(String id) {
		// TODO Auto-generated method stub
		return businessModelBindDao.getBindInfo(id);
	}
	@Override
	public int insertBindInfo(String name, String modelId,String ywId, String showScoreLine) {
		// TODO Auto-generated method stub
		return businessModelBindDao.insertBindInfo(name, modelId,ywId, showScoreLine);
	}
	@Override
	public int updateBindInfo(String name, String modelId,String ywId, String showScoreLine,String id) {
		// TODO Auto-generated method stub
		return businessModelBindDao.updateBindInfo( name, modelId,ywId, showScoreLine ,id);
	}
	@Override
	public int updateBindInfoStatus(String id, String status) {
		// TODO Auto-generated method stub
		return businessModelBindDao.updateBindInfoStatus(id, status);
	}
	@Override
	public int deleteBindInfo(List<String> ids) {
		// TODO Auto-generated method stub
		return businessModelBindDao.deleteBindInfo(ids);
	}
	@Override
	public List<Map<String, Object>> getTopPoints() {
		// TODO Auto-generated method stub
		return businessModelBindDao.getTopPoints("");
	}
	@Override
	public List<Map<String, Object>> getIndexs(String parentId,String modelId) {
		// TODO Auto-generated method stub
		return businessModelBindDao.getIndexs(parentId,modelId);
	}
	@Override
	public Map getRadarData(String tybm, String pcId, String score,String jdToken) {
		Map mo=new HashMap();
		List<Map<String,Object>> listRadars=new ArrayList<Map<String,Object>>();
		String modelId=businessModelBindDao.getModelByPc(pcId);
		String evalInfo=businessModelBindDao.getEvalInfoByScore(Double.parseDouble(score), modelId);
		List<Map<String, Object>> topPoints=businessModelBindDao.getTopPoints(modelId);
		Double scoreShcx=0.0;
		Double maxScoreShcx=0.0;
		boolean isEagle=false;
		int eagleSize=0;
		Double maxScoreExtra=0.0;
		for(int i=0;i<topPoints.size();i++){
			Map<String,Object> radar=new HashMap<String,Object>();
			Map<String, Object> topPoint=topPoints.get(i);
			String parentId=String.valueOf(topPoint.get("indexOrCatId"));
			String name=String.valueOf(topPoint.get("name"));
			Double maxScore=Double.parseDouble(String.valueOf(topPoint.get("weight")));
			List<String> indexIds=new ArrayList<String>();
			getIndexIds(indexIds,parentId,modelId);
			Double scoreI=0.0;
			if(indexIds!=null&&indexIds.size()>0){
				scoreI=businessModelBindDao.getRadarScore(tybm, pcId, indexIds);
			}
			if("加分项".equals(name)&&indexIds.size()>0){
				for(int j=0;j<indexIds.size();j++){
					maxScoreExtra+=businessModelBindDao.selectMaxScore(indexIds.get(i));
				}
				
			}
			if("社会诚信".equals(name)&&indexIds!=null&&indexIds.size()>0){
				scoreShcx+=businessModelBindDao.getRadarScore(tybm, pcId, indexIds);
				maxScoreShcx=maxScore+maxScoreExtra;
			}
			if(("加分项".equals(name)||"减分项".equals(name))&&indexIds!=null&&indexIds.size()>0){
				scoreShcx+=businessModelBindDao.getRadarScore(tybm, pcId, indexIds);
				eagleSize+=indexIds.size();
				isEagle=true;
			}
			if(!"社会诚信".equals(name)&&!"加分项".equals(name)&&!"减分项".equals(name)){
				radar.put("name", name);
				radar.put("score", scoreI);
				radar.put("maxScore", maxScore);
				listRadars.add(radar);
			}
		}
		Map<String,Object> radarShcx=new HashMap<String,Object>();
		radarShcx.put("name", "社会诚信");
		radarShcx.put("score", scoreShcx);
		radarShcx.put("maxScore", maxScoreShcx);
		listRadars.add(radarShcx);
		mo.put("listRadars", listRadars);
		mo.put("evalInfo", evalInfo);
		mo.put("isEagle", isEagle);
		mo.put("eagleSize", getEagleSize(tybm,jdToken));
		return  mo;
	}
	
	public void getIndexIds(List<String>indexsO ,String parentId,String modelId){
		//List<String>indexsF=new ArrayList<String>();
		List<Map<String, Object>> indexs=businessModelBindDao.getIndexs(parentId,modelId);
		for(int i=0;i<indexs.size();i++){
			String type=String.valueOf(indexs.get(i).get("type"));
			String indexOrCatId=String.valueOf(indexs.get(i).get("indexOrCatId"));
			String id=String.valueOf(indexs.get(i).get("id"));
			if("index".equals(type)){
				indexsO.add(id);
				continue;
			}else{
				getIndexIds(indexsO,indexOrCatId,modelId);
			}
		}
		//return indexsF;
	}
	@Override
	public int updateYysx(String batchId, String id,String jdToken) {
		// TODO Auto-generated method stub
		String yysx="";
		String url = urlHelper.getPlatformServerUrl() + "/enterpriseFamilyJa/getYysx.json";
        Map<String, String> params = new HashMap<String, String>(1);
        params.put("batchId", batchId);
        String result = "";
        try {
            // 发送请求
            result = HttpAgent.getInstance().sendHttpPost(url, params, jdToken);
            yysx= JSONObject.parseObject(result, new TypeReference<RestServiceResult<String>>() {
            }).getData();
            businessModelBindDao.updateYysx(yysx,id);
            return 1;
        } catch (Exception e) {
            RestServiceResult<Map<String,Object>> areaData = new RestServiceResult<Map<String,Object>>();
            areaData.setCode(RestServiceResult.CODE_UNKNOW);
            areaData.setMsg("系统异常，请稍后再试！");
            ExceptionLogger.error("远程服务-通过tybm获取饼图调用异常！(businessModelBindServideImpl#countChartByPer) URL:" + url + " Params:"
                    + params.toString() + "Result:" + result, e.getMessage(), e);
            yysx= "";
            return 0;
        }
		
	}
	
	public int getEagleSize(String tybm,String jdToken) {
		// TODO Auto-generated method stub
		Integer size=0;
		String url = urlHelper.getPlatformServerUrl() + "/enterpriseFamilyJa/countEagleEyeByTybm.json";
        Map<String, String> params = new HashMap<String, String>(1);
        params.put("tybm", tybm);
        String result = "";
        try {
            // 发送请求
            result = HttpAgent.getInstance().sendHttpPost(url, params, jdToken);
            size= JSONObject.parseObject(result, new TypeReference<RestServiceResult<Integer>>() {
            }).getData();
            
        } catch (Exception e) {
            RestServiceResult<Map<String,List<Map<String, Object>>>> areaData = new RestServiceResult<Map<String,List<Map<String, Object>>>>();
            areaData.setCode(RestServiceResult.CODE_UNKNOW);
            areaData.setMsg("系统异常，请稍后再试！");
            ExceptionLogger.error("远程服务-通过tybm获取饼图调用异常！(businessModelBindServideImpl#countChartByPer) URL:" + url + " Params:"
                    + params.toString() + "Result:" + result, e.getMessage(), e);
            size= 0;
        }
        return size;
	}
	
	@Override
	public String getEvailInfoScore(String tybm) {
		return businessModelBindDao.getEvailInfoScore(tybm);
	}

	@Transactional
	@Override
	public List<Map<String,Object>> autoScoreUpload(ModelTestPc modelTestPc, String batchId) {
		long start = System.currentTimeMillis();
		modelTestDao.addPc(modelTestPc);
		List<Map<String,Object>> l = this.selectXyjgBatchExport(modelTestPc.getMainType(), batchId);
		businessModelBindDao.initPcDetailByEvalInfo(modelTestPc.getId(), modelTestPc.getModelId(), l);

		double weightAll = 0;

		// 证照指标
		List<Map<String, String>> listZz = modelTestDao.selectZzIndexesByModel(modelTestPc.getModelId());
		for (int i = 0; i < listZz.size(); i++) {
			String indexCatModelId = listZz.get(i).get("indexCatModelId");
			String inputType = listZz.get(i).get("inputType");
			double weightIndex = Double.parseDouble(listZz.get(i).get("weight"));
			String pId = listZz.get(i).get("pId");
			weightIndex = weightIndex / 100;
			weightIndex = new BigDecimal(weightIndex).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			double weight = getWeight(weightIndex, modelTestPc.getModelId(), pId, "category");
			weightAll += weight;
			String type = listZz.get(i).get("type");
			List<Map> rulesSfyzz = modelBaseDao.getRuleListByIndexModelCatForZz(listZz.get(i).get("indexCatModelId"),
					"SFYZZ");
			List<Map> rulesZzsfdq = modelBaseDao.getRuleListByIndexModelCatForZz(listZz.get(i).get("indexCatModelId"),
					"ZZSFDQ");
			double rate = 1;
			if (rulesSfyzz != null && rulesSfyzz.size() > 0 && rulesZzsfdq != null && rulesZzsfdq.size() > 0) {
				rate = 0.5;
			}
			double scoreTrue = 0;
			double scoreFalse = 0;
			if (rulesSfyzz != null && rulesSfyzz.size() > 0) {
				for (int j = 0; j < rulesSfyzz.size(); j++) {
					if (rulesSfyzz.get(j).get("start").equals("1")) {
						scoreTrue = Double.parseDouble(String.valueOf(rulesSfyzz.get(j).get("score")));
						continue;
					}
					if (rulesSfyzz.get(j).get("start").equals("2")) {
						scoreFalse = Double.parseDouble(String.valueOf(rulesSfyzz.get(j).get("score")));
						continue;
					}
				}
			}

			Map<String, Object> cardsMap = new HashMap<>();
			cardsMap.put("type", inputType);
			cardsMap.put("rate", rate);
			cardsMap.put("pcId", modelTestPc.getId());
			cardsMap.put("indexCatModelId", indexCatModelId);
			cardsMap.put("weight", weight);
			cardsMap.put("listSelected", l);

			cardsMap.put("scoreTrue", scoreTrue);
			cardsMap.put("scoreFalse", scoreFalse);
			modelTestDao.insertCardsSfyzzAll(cardsMap);
			if (rulesZzsfdq != null && rulesZzsfdq.size() > 0) {
				for (int j = 0; j < rulesZzsfdq.size(); j++) {
					if (rulesZzsfdq.get(j).get("start").equals("1")) {
						scoreTrue = Double.parseDouble(String.valueOf(rulesZzsfdq.get(j).get("score")));
						continue;
					}
					if (rulesZzsfdq.get(j).get("start").equals("2")) {
						scoreFalse = Double.parseDouble(String.valueOf(rulesZzsfdq.get(j).get("score")));
						continue;
					}
				}
			}

			modelTestDao.insertCardsZzsfdqAll(cardsMap);
		}

		// sql的指标
		List<Map<String, String>> listSql = modelTestDao.selectSqlIndexesByModel(modelTestPc.getModelId());
		for (int i = 0; i < listSql.size(); i++) {
			String sql = listSql.get(i).get("callContent");
			String indexCatModelId = listSql.get(i).get("indexCatModelId");
			String inputType = listSql.get(i).get("inputType");
			double weightIndex = Double.parseDouble(listSql.get(i).get("weight"));
			String pId = listSql.get(i).get("pId");
			weightIndex = weightIndex / 100;
			weightIndex = new BigDecimal(weightIndex).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			double weight = getWeight(weightIndex, modelTestPc.getModelId(), pId, "category");
			weightAll += weight;
			List<Map> listV = xypjRemoteBaseService.autoScoreByIndexSql(modelTestPc.getMainType(), sql, "", batchId);
			if (listV != null && listV.size() > 0) {
				modelTestDao.initIndexInfo(modelTestPc.getId(), indexCatModelId, listV);
			}
			if (StringUtils.isNotBlank(inputType) && "2".equals(inputType)) {
				modelTestDao.updateIndexScoreForDict(modelTestPc.getId(), indexCatModelId, weight);
			} else {
				modelTestDao.updateIndexScore(modelTestPc.getId(), indexCatModelId, weight);
			}

		}
		// 财务指标
		List<Map<String, String>> listFinance = modelTestDao.selectFinanceIndexesByModel(modelTestPc.getModelId());
		for (int i = 0; i < listFinance.size(); i++) {
			String field = listSql.get(i).get("treeElem");
			String indexCatModelId = listSql.get(i).get("indexCatModelId");
			String inputType = listSql.get(i).get("inputType");
			double weightIndex = Double.parseDouble(listSql.get(i).get("weight"));
			String pId = listSql.get(i).get("pId");
			weightIndex = weightIndex / 100;
			weightIndex = new BigDecimal(weightIndex).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			double weight = getWeight(weightIndex, modelTestPc.getModelId(), pId, "category");
			weightAll += weight;
			Map<String, Object> finanxceMap = new HashMap<>();
			finanxceMap.put("field", field);
			finanxceMap.put("pcId", modelTestPc.getId());
			finanxceMap.put("indexCatModelId", indexCatModelId);
			finanxceMap.put("weight", weight);
			finanxceMap.put("listSelected", l);
			modelTestDao.insertFinance(finanxceMap);
			if (StringUtils.isNotBlank(inputType) && "2".equals(inputType)) {
				modelTestDao.updateIndexScoreForDict(modelTestPc.getId(), indexCatModelId, weight);
			} else {
				modelTestDao.updateIndexScore(modelTestPc.getId(), indexCatModelId, weight);
			}

		}
		double leftWeight = 1 - weightAll;
		List<Map> listAll = xypjRemoteBaseService.getAllEnterprise(modelTestPc.getMainType(), "", batchId);
		modelTestDao.initPcDetailByModelTest(modelTestPc.getId(), listAll);
		modelTestDao.deleForUserReport(modelTestPc.getId());
		modelTestDao.updatePcDetailForScore(modelTestPc.getId(), modelTestPc.getInitIndexScore(), leftWeight);
		modelTestDao.updateBgbhByPc(modelTestPc.getId());
		modelTestDao.updatePcDetailRank(modelTestPc.getId(), modelTestPc.getModelId());
		long end = System.currentTimeMillis();
		modelTestDao.updatePcExecuteTime(String.valueOf(end - start), modelTestPc.getId());
		// TODO Auto-generated method stub

		return l;
	}

	@Override
	public void updateImportId(String importId, String tybm, String pcId) {
		businessModelBindDao.updateImportId(importId, tybm, pcId);
	}

	@Override
	public void dzAutoScoreUpload(String qymc,String tybm,String modelId, String dataId,String mainType,Double initIndexScore) {
		businessModelBindDao.dzInitPcDetailByEvalInfo(tybm, modelId, dataId);
		businessModelBindDao.deleteIndexScore(dataId);

		double weightAll = 0;

		// 证照指标
		List<Map<String, String>> listZz = modelTestDao.selectZzIndexesByModel(modelId);
		for (int i = 0; i < listZz.size(); i++) {
			String indexCatModelId = listZz.get(i).get("indexCatModelId");
			String inputType = listZz.get(i).get("inputType");
			String pId = listZz.get(i).get("pId");
			double weightIndex = divide(listZz.get(i).get("weight") ,"100");
			double weight = getWeight(weightIndex, modelId, pId, "category");
			weightAll += weight;
			String type = listZz.get(i).get("type");
			List<Map> rulesSfyzz = modelBaseDao.getRuleListByIndexModelCatForZz(listZz.get(i).get("indexCatModelId"),
					"SFYZZ");
			List<Map> rulesZzsfdq = modelBaseDao.getRuleListByIndexModelCatForZz(listZz.get(i).get("indexCatModelId"),
					"ZZSFDQ");
			double rate = 1;
			if (rulesSfyzz != null && rulesSfyzz.size() > 0 && rulesZzsfdq != null && rulesZzsfdq.size() > 0) {
				rate = 0.5;
			}
			double scoreTrue = 0;
			double scoreFalse = 0;
			if (rulesSfyzz != null && rulesSfyzz.size() > 0) {
				for (int j = 0; j < rulesSfyzz.size(); j++) {
					if (rulesSfyzz.get(j).get("start").equals("1")) {
						scoreTrue = Double.parseDouble(String.valueOf(rulesSfyzz.get(j).get("score")));
						continue;
					}
					if (rulesSfyzz.get(j).get("start").equals("2")) {
						scoreFalse = Double.parseDouble(String.valueOf(rulesSfyzz.get(j).get("score")));
						continue;
					}
				}
			}

			Map<String, Object> cardsMap = new HashMap<>();
			cardsMap.put("type", inputType);
			cardsMap.put("rate", rate);
			cardsMap.put("pcId", dataId);
			cardsMap.put("indexCatModelId", indexCatModelId);
			cardsMap.put("weight", weight);
			cardsMap.put("tybm", tybm);

			cardsMap.put("scoreTrue", scoreTrue);
			cardsMap.put("scoreFalse", scoreFalse);
			businessModelBindDao.dzInsertCardsSfyzzAll(cardsMap);
			if (rulesZzsfdq != null && rulesZzsfdq.size() > 0) {
				for (int j = 0; j < rulesZzsfdq.size(); j++) {
					if (rulesZzsfdq.get(j).get("start").equals("1")) {
						scoreTrue = Double.parseDouble(String.valueOf(rulesZzsfdq.get(j).get("score")));
						continue;
					}
					if (rulesZzsfdq.get(j).get("start").equals("2")) {
						scoreFalse = Double.parseDouble(String.valueOf(rulesZzsfdq.get(j).get("score")));
						continue;
					}
				}
			}

			businessModelBindDao.dzInsertCardsZzsfdqAll(cardsMap);
		}

		// sql的指标
		List<Map<String, String>> listSql = modelTestDao.selectSqlIndexesByModel(modelId);
		for (int i = 0; i < listSql.size(); i++) {
			String sql = listSql.get(i).get("callContent");
			String indexCatModelId = listSql.get(i).get("indexCatModelId");
			String inputType = listSql.get(i).get("inputType");
			String pId = listSql.get(i).get("pId");
			double weightIndex = divide(listSql.get(i).get("weight") ,"100");
			double weight = getWeight(weightIndex, modelId, pId, "category");
			weightAll += weight;
			List<Map> listV = xypjRemoteBaseService.autoScoreByIndexSql(mainType, sql, tybm, null);
			if (listV != null && listV.size() > 0) {
				modelTestDao.initIndexInfo(dataId, indexCatModelId, listV);
			}
			if (StringUtils.isNotBlank(inputType) && "2".equals(inputType)) {
				modelTestDao.updateIndexScoreForDict(dataId, indexCatModelId, weight);
			} else {
				modelTestDao.updateIndexScore(dataId, indexCatModelId, weight);
			}
		}
		// 财务指标
		List<Map<String, String>> listFinance = modelTestDao.selectFinanceIndexesByModel(modelId);
		for (int i = 0; i < listFinance.size(); i++) {
			String field = listSql.get(i).get("treeElem");
			String indexCatModelId = listSql.get(i).get("indexCatModelId");
			String inputType = listSql.get(i).get("inputType");
			String pId = listSql.get(i).get("pId");
			double weightIndex = divide(listFinance.get(i).get("weight") ,"100");
			double weight = getWeight(weightIndex, modelId, pId, "category");
			weightAll += weight;
			Map<String, Object> finanxceMap = new HashMap<>();
			finanxceMap.put("field", field);
			finanxceMap.put("pcId", dataId);
			finanxceMap.put("indexCatModelId", indexCatModelId);
			finanxceMap.put("weight", weight);
			finanxceMap.put("tybm", tybm);
			businessModelBindDao.dzInsertFinance(finanxceMap);
			if (StringUtils.isNotBlank(inputType) && "2".equals(inputType)) {
				modelTestDao.updateIndexScoreForDict(dataId, indexCatModelId, weight);
			} else {
				modelTestDao.updateIndexScore(dataId, indexCatModelId, weight);
			}

		}
		double leftWeight = 1 - weightAll;
		businessModelBindDao.dzInitPcDetailByModelTest(tybm,qymc,dataId);
		modelTestDao.deleForUserReport(dataId);
		modelTestDao.updatePcDetailForScore(dataId, initIndexScore, leftWeight);
		modelTestDao.updatePcDetailRank(dataId, modelId);
	}

	@Override
	public Map dzGetScoreData(String modelId,String tybm, String dataId) {
		Map mo=new HashMap();
		List<Map<String,Object>> listRadars=new ArrayList<Map<String,Object>>();

		String score=businessModelBindDao.dzGetEvailInfoScore(dataId);

		String evalInfo=businessModelBindDao.getEvalInfoByScore(Double.parseDouble(score), modelId);
		List<Map<String, Object>> topPoints=businessModelBindDao.getTopPoints(modelId);
		Double scoreShcx=0.0;
		Double maxScoreShcx=0.0;
		Double maxScoreExtra=0.0;
		for(int i=0;i<topPoints.size();i++){
			Map<String,Object> radar=new HashMap<String,Object>();
			Map<String, Object> topPoint=topPoints.get(i);
			String parentId=String.valueOf(topPoint.get("indexOrCatId"));
			String name=String.valueOf(topPoint.get("name"));
			Double maxScore=Double.parseDouble(String.valueOf(topPoint.get("weight")));
			List<String> indexIds=new ArrayList<String>();
			getIndexIds(indexIds,parentId,modelId);
			Double scoreI=0.0;
			if(indexIds!=null&&indexIds.size()>0){
				scoreI=businessModelBindDao.getRadarScore(tybm, dataId, indexIds);
			}
			if("加分项".equals(name)&&indexIds.size()>0){
				for(int j=0;j<indexIds.size();j++){
					maxScoreExtra+=businessModelBindDao.selectMaxScore(indexIds.get(i));
				}
			}

			if("社会诚信".equals(name)&&indexIds!=null&&indexIds.size()>0){
				scoreShcx+=businessModelBindDao.getRadarScore(tybm, dataId, indexIds);
				maxScoreShcx=maxScore+maxScoreExtra;
			}

			if(("加分项".equals(name)||"减分项".equals(name))&&indexIds!=null&&indexIds.size()>0){
				scoreShcx+=businessModelBindDao.getRadarScore(tybm, dataId, indexIds);
			}

			if(!"社会诚信".equals(name)&&!"加分项".equals(name)&&!"减分项".equals(name)){
				radar.put("name", name);
				radar.put("score", scoreI);
				radar.put("maxScore", maxScore);
				listRadars.add(radar);
			}
		}

		Map<String,Object> radarShcx=new HashMap<String,Object>();
		radarShcx.put("name", "社会诚信");
		radarShcx.put("score", scoreShcx);
		radarShcx.put("maxScore", maxScoreShcx);
		listRadars.add(radarShcx);
		mo.put("listRadars", listRadars);
		mo.put("evalInfo", evalInfo);
		mo.put("evalInfoScore",score);
		return  mo;
	}

	public double getWeight(double weight, String modelId, String indexCatModelId, String type) {
		Map<String, String> m = modelTestDao.getParentWeight(modelId, indexCatModelId, type);
		weight=divide(String.valueOf(multiply(m.get("weight") ,String.valueOf(weight))),"100");
		type = "category";
		if (String.valueOf(m.get("pId")).equals("0") || String.valueOf(m.get("pId")).equals("")) {
			return weight;
		} else {
			return getWeight(weight, modelId, String.valueOf(m.get("pId")), type);
		}
	}

	private List<Map<String,Object>> selectXyjgBatchExport(String mainType,String batchId) {
		Map<String, String> params = new HashMap<String, String>(1);
		params.put("mainType", mainType);
		params.put("batchId", batchId);
		String url = urlHelper.getPlatformServerUrl() + "/enterpriseFamilyJa/selectXyjgBatchExport.json";
		String result = "";
		try {
			// 发送请求
			result = HttpAgent.getInstance().sendHttpPost(url, params, null);
			return JSONObject.parseObject(result, new TypeReference<RestServiceResult<List<Map<String,Object>>>>() {
			}).getData();
		} catch (Exception e) {
			RestServiceResult<List<Map<String,Object>>> data = new RestServiceResult<>();
			data.setCode(RestServiceResult.CODE_UNKNOW);
			data.setMsg("系统异常，请稍后再试！");
			ExceptionLogger.error("远程服务-远程调用信用监管信息异常！(BusinessModelBindServiceImpl#selectBatchExport) URL:" + url
					+ " Params:" + params.toString() + "Result:" + result, e.getMessage(), e);
			return data.getData();
		}
	}

	public double multiply(String a,String b){
		BigDecimal a1 = new BigDecimal(a);
		BigDecimal b1 = new BigDecimal(b);
		return a1.multiply(b1).doubleValue();
	}

	private double divide(String a,String b){
		BigDecimal a1 = new BigDecimal(a);
		BigDecimal b1 = new BigDecimal(b);
		return a1.divide(b1).doubleValue();
	}
	
	public List<SysOfficeEntity> getTopLevelDept(){
		String url = urlHelper.getBaseServerUrl() + "/auth/getRootOffices.do";
		String sendHttpPost = HttpAgent.getInstance().sendHttpPost(url, "");

		RestServiceResult<List<SysOfficeEntity>> rss = JSON.parseObject(sendHttpPost,
				new TypeReference<RestServiceResult<List<SysOfficeEntity>>>() {
				});
		return rss.getData();
	}
	
	public SysOfficeEntity getOfficeById(String officeId){
		String url = urlHelper.getBaseServerUrl() + "/auth/getOfficeById";
		 Map<String, String> params = new HashMap<String, String>(1);
	     params.put("officeId", officeId);
		String sendHttpPost = HttpAgent.getInstance().sendHttpPost(url,params,"");

		RestServiceResult<SysOfficeEntity> rss = JSON.parseObject(sendHttpPost,
				new TypeReference<RestServiceResult<SysOfficeEntity>>() {
				});
		return rss.getData();
	}
	
	
	
	public List<String>  getAlreadyDistributeRecord(String id){
		return businessModelBindDao.getAlreadyDistributeRecord(id);
	}
	
	 @Override
	  @Transactional
	    public void distributeCommonResource(String id, List<Map<String, String>> depts) {

		 businessModelBindDao.delDistributeCube(id);

	        for (Map<String, String> map : depts) {

	        	businessModelBindDao.addDeptCube(map.get("deptId"), id);
	        }
	    }
	 
	 public int  isAddDept(String deptId,String id){
		 return businessModelBindDao.isAddDept(deptId, id);
	 }
	 
	 public int  isUpdateDept(String modelId,String ywId,String deptId,String id){
		 return businessModelBindDao.isUpdateDept(modelId, ywId, deptId, id);
	 }
	 
}
